package com.devicemantra.coordinate.ds.tests;
import static java.util.logging.Level.WARNING;

import com.devicemantra.coordinate.dataobjects.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.devicemantra.coordinate.dataobjects.CDepartmentFactory;
import com.devicemantra.coordinate.interfaces.call.CCallMessage;
import com.devicemantra.coordinate.interfaces.email.CSendEmail;
import com.devicemantra.coordinate.tasks.CTask;
import com.devicemantra.coordinate.tasks.CTaskFactory;
import com.devicemantra.coordinate.ds.tests.PMF;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class AuthenticateMobileNumber extends HttpServlet 
{
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException 
	{
		final  Logger log = Logger.getAnonymousLogger();
		String lMessageId = req.getParameter("id");
		System.out.println("Id we got was " + lMessageId);
		
		boolean lDoesExist = true;
		String lAuthMesgId = lMessageId;
		PersistenceManager lPMF = PMF.get().getPersistenceManager();
		CAuthMobileMessage lAuthMessageObj = null;
		try
		{
			lAuthMessageObj = lPMF.getObjectById(CAuthMobileMessage.class,lAuthMesgId);
		} catch(JDOObjectNotFoundException e)
		{
			lDoesExist = false;
		}finally {
			lPMF.close();
		}
		
		if(false == lDoesExist) 
		{
			System.out.println("FATAL ERROR: The message id does not exist :" + lAuthMesgId);
			return; 
		}
		
		CTask lTask = CTaskFactory.createNewCallTask();
		lTask.setTaskUrl("/AuthCallTask"); 
		lTask.addParameter("mobile_number",lAuthMessageObj.getAuthMobileNumber());
		lTask.addParameter("call_responder_id",lAuthMessageObj.getMessageId());
		CTaskFactory.addTaskToQueue(lTask); 
		//resp.getOutputStream().println("Add call task with id " + lCallMesg.getMessageKey());
		
		//log.info("Queued Email tasks for execution !");
		System.out.println("Forwarding request to /modules/administration/auth/authenticate.jsp).forward(req,resp)");
		try {
			req.getSession().setAttribute("id", lAuthMessageObj.getMessageId());
			System.out.println("session id set to " + lAuthMessageObj.getMessageId());
			req.getRequestDispatcher("/modules/administration/auth/authenticate.jsp").forward(req,resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
}

